<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/page/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/page/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/page/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/page/images/logo.svg" color="#222">

<link rel="stylesheet" href="/page/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" integrity="sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"assd12138.gitee.io","root":"/page/","images":"/page/images","scheme":"Gemini","darkmode":false,"version":"8.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/page/search.json","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/page/js/config.js"></script>
<meta name="description" content="使用MediaDevices中提供的接口实现前端进行网页的录屏，并实时转化为二进制数据（视频）">
<meta property="og:type" content="article">
<meta property="og:title" content="使用媒体api实现网页录屏">
<meta property="og:url" content="https://assd12138.gitee.io/page/2021/11/13/%E4%BD%BF%E7%94%A8%E5%AA%92%E4%BD%93api%E5%AE%9E%E7%8E%B0%E7%BD%91%E9%A1%B5%E5%BD%95%E5%B1%8F/index.html">
<meta property="og:site_name" content="爱爱爱呵风他">
<meta property="og:description" content="使用MediaDevices中提供的接口实现前端进行网页的录屏，并实时转化为二进制数据（视频）">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-13T12:44:35.000Z">
<meta property="article:modified_time" content="2022-05-09T03:18:13.063Z">
<meta property="article:author" content="爱爱爱呵风他">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="尝鲜">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://assd12138.gitee.io/page/2021/11/13/%E4%BD%BF%E7%94%A8%E5%AA%92%E4%BD%93api%E5%AE%9E%E7%8E%B0%E7%BD%91%E9%A1%B5%E5%BD%95%E5%B1%8F/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://assd12138.gitee.io/page/2021/11/13/%E4%BD%BF%E7%94%A8%E5%AA%92%E4%BD%93api%E5%AE%9E%E7%8E%B0%E7%BD%91%E9%A1%B5%E5%BD%95%E5%B1%8F/","path":"2021/11/13/使用媒体api实现网页录屏/","title":"使用媒体api实现网页录屏"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>使用媒体api实现网页录屏 | 爱爱爱呵风他</title>
  




  <noscript>
    <link rel="stylesheet" href="/page/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/page/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">爱爱爱呵风他</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/page/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/page/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-archives"><a href="/page/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8MediaDevices-getDisplayMedia%E8%8E%B7%E5%8F%96%E5%B1%8F%E5%B9%95"><span class="nav-number">1.</span> <span class="nav-text">使用MediaDevices.getDisplayMedia获取屏幕</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E8%8E%B7%E5%8F%96%E5%88%B0%E7%9A%84%E8%A7%86%E9%A2%91%E6%B5%81"><span class="nav-number">2.</span> <span class="nav-text">使用获取到的视频流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E7%AE%80%E6%98%93%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="nav-number">3.</span> <span class="nav-text">更简易的方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E4%BE%8B"><span class="nav-number">4.</span> <span class="nav-text">实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="爱爱爱呵风他"
      src="https://s1.ax1x.com/2020/08/26/dWnF58.jpg">
  <p class="site-author-name" itemprop="name">爱爱爱呵风他</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/page/archives/">
          <span class="site-state-item-count">24</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/page/tags/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-cn" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdn.jsdelivr.net/npm/@creativecommons/vocabulary@2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://assd12138.gitee.io/page/2021/11/13/%E4%BD%BF%E7%94%A8%E5%AA%92%E4%BD%93api%E5%AE%9E%E7%8E%B0%E7%BD%91%E9%A1%B5%E5%BD%95%E5%B1%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s1.ax1x.com/2020/08/26/dWnF58.jpg">
      <meta itemprop="name" content="爱爱爱呵风他">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱爱爱呵风他">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          使用媒体api实现网页录屏
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-11-13 20:44:35" itemprop="dateCreated datePublished" datetime="2021-11-13T20:44:35+08:00">2021-11-13</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-09 11:18:13" itemprop="dateModified" datetime="2022-05-09T11:18:13+08:00">2022-05-09</time>
      </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>使用<code>MediaDevices</code>中提供的接口实现前端进行网页的录屏，并实时转化为二进制数据（视频）</p>
<span id="more"></span>

<h2 id="使用MediaDevices-getDisplayMedia获取屏幕"><a href="#使用MediaDevices-getDisplayMedia获取屏幕" class="headerlink" title="使用MediaDevices.getDisplayMedia获取屏幕"></a>使用<code>MediaDevices.getDisplayMedia</code>获取屏幕</h2><p>通过<code>MediaDevices.getDisplayMedia</code>，可以在征得用户允许的情况下，获得窗口或者整个屏幕的录制权限（取决于用户的选择），其使用promise风格的方式进行用户权限获取</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">try</span>&#123;</span><br><span class="line">    stream = <span class="keyword">await</span> <span class="title class_">MediaDevices</span>.<span class="title function_">getDisplayMedia</span>(&#123;</span><br><span class="line">      <span class="attr">video</span>:<span class="literal">true</span></span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;<span class="keyword">catch</span>(err)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(err)</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该函数接收一个称作<code>constraints</code>的参数，即可以利用此参数配置一些类似采样率之类的专业的音视频参数，但是支持度可能存在一定的问题</p>
<h2 id="使用获取到的视频流"><a href="#使用获取到的视频流" class="headerlink" title="使用获取到的视频流"></a>使用获取到的视频流</h2><p>使用<code>MediaRecorder</code>来进行流的处理，可以进行实时的包装，停止录屏后将记录到的流打包成为二进制大对象(blob)并置入页面的视频源中，也可以利用页面媒体元素中的<code>srcObject</code>进行更简单的操作</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 通过MediaRecorder进行录制重放</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 检测指定的mime类型能否被MediaRecorder录制</span></span><br><span class="line"><span class="keyword">const</span> mimeType = <span class="title class_">MediaRecorder</span>.<span class="title function_">isTypeSupported</span>(<span class="string">&#x27;video/webm; codecs=vp8&#x27;</span>)</span><br><span class="line">? <span class="string">&#x27;video/webm; codecs=vp9&#x27;</span></span><br><span class="line">: <span class="string">&#x27;video/webm&#x27;</span></span><br><span class="line"><span class="keyword">const</span> recorder = <span class="keyword">new</span> <span class="title class_">MediaRecorder</span>(stream,&#123;mimeType&#125;)</span><br><span class="line"><span class="keyword">let</span> chulks = []</span><br><span class="line"><span class="comment">// 为recorder绑定事件，处理组装数据和流停止的后续处理</span></span><br><span class="line">recorder.<span class="title function_">addEventListener</span>(<span class="string">&#x27;dataavailable&#x27;</span>,<span class="function"><span class="params">e</span>=&gt;</span>chulks.<span class="title function_">push</span>(e.<span class="property">data</span>))</span><br><span class="line">recorder.<span class="title function_">addEventListener</span>(<span class="string">&#x27;stop&#x27;</span>,<span class="function"><span class="params">_</span>=&gt;</span>&#123;</span><br><span class="line">  <span class="comment">// 二进制大对象的处理，将chulks转为内存映射的blob地址</span></span><br><span class="line">  <span class="keyword">const</span> blob = <span class="keyword">new</span> <span class="title class_">Blob</span>(chulks,&#123;</span><br><span class="line">    <span class="attr">type</span>: chulks[<span class="number">0</span>].<span class="property">type</span></span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="comment">// 将blob挂载到video元素上</span></span><br><span class="line">  video.<span class="property">src</span> = <span class="variable constant_">URL</span>.<span class="title function_">createObjectURL</span>(blob)</span><br><span class="line">&#125;)</span><br><span class="line">recorder.<span class="title function_">start</span>()</span><br></pre></td></tr></table></figure>

<h2 id="更简易的方式"><a href="#更简易的方式" class="headerlink" title="更简易的方式"></a>更简易的方式</h2><p>使用实验性的<code>srcObject</code>，可以直接将视频流绑定到页面的多媒体元素上</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">video.<span class="property">srcObject</span> = stream</span><br></pre></td></tr></table></figure>

<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2>
<fieldset>
  <legend>停止后再观看</legend>
  <video class="video" width="600px" controls></video>
</fieldset>
<fieldset>
  <legend>实时录屏的video元素</legend>
  <video class="video2" width="600px" autoplay></video>
</fieldset>
<button class="record-btn">开始录制</button>
<script>
const recordBtn = document.querySelector('.record-btn')
const video = document.querySelector('.video')
const video2 = document.querySelector('.video2')
recordBtn.addEventListener('click',async ()=>{
  const stream = await navigator.mediaDevices.getDisplayMedia({
    video:true,
    audio:true
  })
  video2.srcObject = stream

  const mimeType = MediaRecorder.isTypeSupported('video/webm; codecs=vp8')
  ? 'video/webm; codecs=vp8'
  : 'video/webm'
  const recorder = new MediaRecorder(stream,{mimeType})
  let chulks = []
  recorder.addEventListener('dataavailable',e=>chulks.push(e.data))
  recorder.addEventListener('stop',_=>{
    const blob = new Blob(chulks,{
      type: chulks[0].type
    })
    video.src = URL.createObjectURL(blob)
  })
  recorder.start()
})
</script>


<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>在<a target="_blank" rel="noopener" href="https://youtu.be/Df2U9-R-OJs">Chrome Dev Submit 2021</a>的线上宣讲会中，邀请到了<a target="_blank" rel="noopener" href="https://www.kapwing.com/">kapwing</a>来分享他们如何利用最新的web多媒体api搭建在线多媒体编辑器</p>
<p>正在使用的Api</p>
<table>
<thead>
<tr>
<th>Api</th>
<th>实现的功能</th>
</tr>
</thead>
<tbody><tr>
<td>IndexedDB</td>
<td>尽可能将数据存储在本地以支持高性能的编辑</td>
</tr>
<tr>
<td>Web Sockets Api</td>
<td>允许用户进行实时协作</td>
</tr>
<tr>
<td>Web Audio Api</td>
<td>加载音轨，实现对声音的编辑操作</td>
</tr>
<tr>
<td>Media Recorder Api</td>
<td>记录网络摄像头和屏幕，实现表情记录等功能</td>
</tr>
<tr>
<td>Web Workers</td>
<td>将复杂的运算分流到workers中，避免影响主线程性能</td>
</tr>
<tr>
<td>PWA</td>
<td>渐进式webapp，第一次加载完成后，使应用可以安装到桌面</td>
</tr>
</tbody></table>
<p>未来计划使用的功能</p>
<table>
<thead>
<tr>
<th>Api</th>
<th>实现的功能</th>
</tr>
</thead>
<tbody><tr>
<td>Web Codecs</td>
<td>加速帧绘制</td>
</tr>
<tr>
<td>WebGL</td>
<td>更复杂的动画效果</td>
</tr>
<tr>
<td>Media Source Extensions</td>
<td>加速片段间的切换</td>
</tr>
</tbody></table>
<p>除此之外，大会上还介绍了<a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries">基于容器的媒体查询功能</a>，探讨了Google内置隐私沙盒的功能并逐渐限制第三方cookie。谷歌对浏览器的垄断，导致了chrome大步走在浏览器的最前沿，未来还会有哪些各种各样的新奇技术，或许让前端工程师包罗一切的话，头发都不够掉的🤣</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/page/tags/JavaScript/" rel="tag"># JavaScript</a>
              <a href="/page/tags/%E5%B0%9D%E9%B2%9C/" rel="tag"># 尝鲜</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/page/2021/10/12/%E5%8F%96%E8%89%B2%E5%99%A8/" rel="prev" title="取色器">
                  <i class="fa fa-chevron-left"></i> 取色器
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/page/2021/11/14/Vue%E5%93%8D%E5%BA%94%E5%BC%8F%E7%9A%84%E5%9F%BA%E7%A1%80%E5%8E%9F%E7%90%86/" rel="next" title="Vue响应式的基础原理">
                  Vue响应式的基础原理 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">爱爱爱呵风他</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script size="300" alpha="0.6" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/page/js/comments.js"></script><script src="/page/js/utils.js"></script><script src="/page/js/motion.js"></script><script src="/page/js/next-boot.js"></script>

  
<script src="https://cdn.jsdelivr.net/npm/hexo-generator-searchdb@1.4.0/dist/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/page/js/third-party/search/local-search.js"></script>





  




<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"assd12138/utterancesComment","issue_term":"pathname","theme":"preferred-color-scheme"}</script>
<script src="/page/js/third-party/comments/utterances.js"></script>

</body>
</html>
